package persist

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"log"
	"time"
	_ "time/tzdata"
)

type SqlxDriver struct {
	*sqlx.DB //数据库驱动，封装基础数据库操作方法
}

func (driver *SqlxDriver) DriverName() string {
	return "SqlxDriver"
}

func (driver *SqlxDriver) openConn(cfg *config) IxDriver {
	// 本地化也可以写成[loc=Local]
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=True&charset=utf8mb4&loc=Asia%%2FShanghai", cfg.username, cfg.password, cfg.host, cfg.port, cfg.dbName)

	sqlxDB, err := sqlx.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("Error opening database: %v", err)
	}

	err = sqlxDB.Ping()
	if err != nil {
		log.Fatalf("Error pinging database: %v", err)
	}
	log.Printf("Successfully connected to MySQL database With 【%s】", driver.DriverName())

	// mysql默认28800秒(8小时)断开未活动连接
	// show variables like 'wait_timeout';
	sqlxDB.SetConnMaxLifetime(time.Second * 28000)

	//sqlxDB.SetMaxIdleConns(2)  // 设置最大空闲连接数
	//sqlxDB.SetMaxOpenConns(20) // 设置最大打开连接数

	driver.DB = sqlxDB
	return driver
}

func (driver *SqlxDriver) closeConn() error {
	if driver.DB != nil {
		return driver.Close()
	}
	return nil
}
